import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 验证码输入框
class VerificationCodeUtil extends StatefulWidget {
  /// 验证码列表
  final List<String>? codeList;

  final ValueChanged<String>? onChanged;

  VerificationCodeUtil({
    Key? key,
    this.codeList,
    this.onChanged,
  }) : super(key: key);

  @override
  _VerificationCodeUtilState createState() => _VerificationCodeUtilState();
}

class _VerificationCodeUtilState extends State<VerificationCodeUtil> {
  TextEditingController _controller = TextEditingController();
  FocusNode _focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    Color textColor = Theme.of(context).primaryColor;
    return Stack(
      children: <Widget>[
        EditableText(
          controller: _controller,
          focusNode: _focusNode,
          // 指定键盘外观，仅iOS有效
          keyboardAppearance: Brightness.dark,
          // 只能为数字、6位
          inputFormatters: [LengthLimitingTextInputFormatter(6)],
          // 隐藏光标与字体颜色，达到隐藏输入框的目的
          cursorColor: Colors.transparent,
          cursorWidth: 0,
          autofocus: true,
          textAlign: TextAlign.center,
          backgroundCursorColor: Colors.transparent,
          style: TextStyle(color: Colors.transparent, fontSize: 18.0),
          onChanged: widget.onChanged,
        ),
        GestureDetector(
          onTap: () {
            /// 一直怼，会有概率造成键盘抖动，加一个键盘时候弹出判断
            if (MediaQuery.of(context).viewInsets.bottom < 10) {
              final focusScope = FocusScope.of(context);
              focusScope.unfocus();
              Future.delayed(
                Duration.zero,
                () => focusScope.requestFocus(_focusNode),
              );
            }
          },
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: List.generate(
                widget.codeList!.length,
                (i) => _buildInputWidget(i, textColor),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 单个验证码输入框布局
  Widget _buildInputWidget(int index, Color textColor) {
    return Container(
      height: 32.0,
      width: 32.0,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        border: Border.all(
          width: 0.6,
          color: widget.codeList![index].isNotEmpty ? textColor : Colors.grey,
        ),
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: Text(
        widget.codeList![index],
        style: TextStyle(fontSize: 18.0),
      ),
    );
  }
}
